// pages/public_tasks/do_picture_task/do_picture_task.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    taskId: null,
    currentTaskIndex: 0,
    totalCount: null,
    taskItems: [],
    showModal: false,
    layerHidden: true,
    isCommit: false
  },
  /**
   * 关闭按钮
   */
  closeBtn: function () {
    console.log('closeBtn');
    this.setData({
      layerHidden: false
    });
  },
  cancelBtn: function () {
    this.setData({
      layerHidden: true
    })
  },
  leaveBtn: function () {
    wx.switchTab({
      url: '../task_list/task_list'
    })
  },
  previewImg: function () {
    wx.previewImage({
      current: '', 
      urls: [
        this.data.taskItems[this.data.currentTaskIndex].pictureAnswerFilePath
      ] 
    })
  },
  previewDemoImg: function (e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: '',
      urls: [
        url
      ]
    })
  },

  invokeCamera: function () {

    if (this.data.taskItems[this.data.currentTaskIndex].pictureAnswerFilePath) {
      wx.showModal({
        content: '最多只能上传一张图片哦~',
        showCancel: false
      })
      return;
    }

    var _this = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: function (res) {
        console.log(res);

        wx.showLoading({
          mask: true
        })
        var tempFilePaths = res.tempFilePaths
        // _this.data.taskItems[_this.data.currentTaskIndex].pictureAnswerFilePath = tempFilePaths[0];

        // _this.setData({
        //   taskItems: _this.data.taskItems,
        // });

        wx.uploadFile({
          url: app.globalData.apiDomain + 'crowdsource/task/uploadFileForSubject',
          header: { 'Content-Type': 'multipart/form-data', 'token': app.globalData.token },
          //filePath: _this.data.taskItems[_this.data.currentTaskIndex].speechFilePath,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            "projectTypeId": 3,
            "subjectId": _this.data.taskItems[_this.data.currentTaskIndex].id,
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            if (data.status === 'ok') {
              _this.data.taskItems[_this.data.currentTaskIndex].pictureAnswerFilePath = data.object;

              _this.setData({
                taskItems: _this.data.taskItems,
              });
              
              /*
              音频文件上传成功后更新视频文件地址
              _this.data.taskItems[_this.data.currentTaskIndex].speechFilePath = data.object
              _this.setData({
                taskItems: _this.data.taskItems,
              });
              */
            }else {
              app.responseCheck(_this, data, '');
            }
          },
          fail: function (res) {
            wx.showModal({
              content: '不好，挂了！管理员哥哥正在赶来~',
              showCancel: false
            })
          },
          complete: function (res) {
            wx.hideLoading();
          }
        })

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var _this = this;
    this.setData({
      taskId: options.id,
    });

    wx.setNavigationBarTitle({
      title: options.projectName
    })

    _this.picTask();
    app.userLoginReadyCallback = res => {
      _this.picTask();
    }
  },

  picTask: function(){
    var _this = this;
    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/doTask',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 3
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        console.log(res);
        let data = res.data;
        if (data.status === 'ok') {
          if (!data.object.picture) {
            wx.showModal({
              content: '任务竟然不存在！还是去看看别的吧~ ',
              showCancel: false
            })
          }
          var index = data.object.picture.order - 1;
          _this.data.taskItems[index] = data.object.picture;

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
            totalCount: data.object.taskCount,
          });

        } else {
          app.responseCheck(_this, data, '');
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false,
        })
      }
    })
  },

  /**
     * 任务切换 - 上一条
     */
  taskSwitchPrevious: function () {
    var _this = this;

    if (_this.data.taskItems[_this.data.currentTaskIndex - 1]) {
      _this.setData({
        currentTaskIndex: _this.data.currentTaskIndex - 1,
      });
      return false;
    }

    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];
    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/previousSubject',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 3,
        'subjectId': taskItem.id,
        'currentOrder': taskItem.order,
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        console.log(data);
        if (data.status === 'ok') {
          if (!data.object) {
            wx.showModal({
              content: '不好，挂了！管理员哥哥正在赶来~',
              showCancel: false
            });
            return
          }
          
          var index = data.object.order - 1;
          _this.data.taskItems[index] = data.object;

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
          });
        }else {
          app.responseCheck(_this, data, '');
        }
      },
      fail: function (e) {
      }
    })
  },
  /**
   * 任务切换 - 下一条
   */
  taskSwitchNext: function () {
    var _this = this;
    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];

    if (!taskItem.pictureAnswerFilePath) {
      wx.showModal({
        content: '咦，好像没照上啊，再拍一次吧~',
        showCancel: false
      })
      return false;
    }

    if (_this.data.taskItems[_this.data.currentTaskIndex + 1]) {
      _this.setData({
        currentTaskIndex: _this.data.currentTaskIndex + 1,
      });
      return false;
    }

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/nextSubject',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 3,
        'subjectId': taskItem.id,
        'currentOrder': taskItem.order,
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        console.log(data);
        if (data.status === 'ok') {

          if (!data.object) {
            wx.showModal({
              content: '不好，挂了！管理员哥哥正在赶来~',
              showCancel: false
            });
            return
          }

          var index = data.object.order - 1;
          _this.data.taskItems[index] = data.object;

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
          });

        }else {
          app.responseCheck(_this, data, '');
        }
      },
      fail: function (e) {
      }
    })
  },

  /**
     * 确认提交
     */
  commitTask: function () {
    let _this = this;
    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];

    if (!taskItem.pictureAnswerFilePath) {
      wx.showModal({
        content: '咦，好像没照上啊，再拍一次吧~',
        showCancel: false
      })
      return false;
    }

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/commitTask/' + _this.data.taskId,
      method: 'POST',
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        console.log(data);
        if (data.status === 'ok') {

          //跳转到我的任务列表
          _this.setData({
            isCommit: true
          });
          wx.showModal({
            content: '任务提交成功，小姐姐们会尽快审核的，请耐心等待呦！',
            showCancel: false,
            success: function (e) {
              wx.switchTab({
                url: '../../my_tasks/task_list/task_list'
              })
            }
          })
        }else {
          app.responseCheck(_this, data, '');
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })

  },

  deleteImg: function () {
    var _this = this;
    var tmp_answer_pic = this.data.taskItems[this.data.currentTaskIndex].pictureAnswerFilePath;
    var tmp_project_id = this.data.taskItems[this.data.currentTaskIndex].id;

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/deleteForSubject',
      method: 'POST',
      data: {
        'projectTypeId': 3,
        'subjectId': tmp_project_id,
        'path': tmp_answer_pic
      },
      header: { 'Content-Type': 'application/x-www-form-urlencoded', 'token': app.globalData.token },
      success: function (res) {
        console.log(res);
        if (res.data.status == 'ok') {
          _this.data.taskItems[_this.data.currentTaskIndex].pictureAnswerFilePath = "";
          _this.setData({
            taskItems: _this.data.taskItems
          });
        }else {
          app.responseCheck(_this, res.data,"/pages/public_tasks/do_picture_task/do_picture_task");
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 正常提交不提示
    if (!this.data.isCommit) {
      wx.showModal({
        content: '任务未完成，可以从我的任务重新进入',
        showCancel: false
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})